package com.example.demo.controller;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.*;

@RestController
public class FileController {

    @Value("classpath:data/test.pdf")
    private Resource resource;

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<byte[]> downFile(String e) throws IOException {

        ResponseEntity<byte[]> result = null;
        if(e != null){
            throw new RuntimeException("发生异常！");
        }
        try {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            InputStream inputStream = resource.getInputStream();
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            HttpHeaders heads = new HttpHeaders();
            heads.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=lr.xls");
            heads.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);

            result = new ResponseEntity<byte[]>(output.toByteArray(), heads, HttpStatus.OK);
        }finally {

        }
        return result;
    }


    public void sss(){
        FileItem fileItem = new DiskFileItemFactory().createItem("file"
                , MediaType.TEXT_PLAIN_VALUE
                , true
                , resource.getFilename());
        try (InputStream input = resource.getInputStream();
             OutputStream os = fileItem.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

    }

}
